package com.schoolegard.services.impl;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.schoolegard.services.RoleService;
import com.schoolgard.dao.RoleDao;
import com.schoolgard.dao.RolePrivilegeDao;
import com.schoolgard.entitybean.Role;
import com.schoolgard.entitybean.RolePrivilege;

public class RoleServiceImpl implements RoleService {

	//系统用户
	private RoleDao roleDao;
	private RolePrivilegeDao rolePrivilegeDao;
	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}
	public void setRolePrivilegeDao(RolePrivilegeDao rolePrivilegeDao) {
		this.rolePrivilegeDao = rolePrivilegeDao;
	}

	@Override
	public List<Role> findAllRole() {
		return roleDao.findAll();
	}
	@Override
	public Role findById(Long id) {
		return roleDao.findById(id);
	}
	@Override
	public void saveOrUpdate(Role role) {
		roleDao.createOrModify(role);
	}
	@Override
	public void delete(Long id) {
		Role role = findById(id);
		Set<RolePrivilege> rp = role.getRolePrivileges();
		Iterator<RolePrivilege> itera = rp.iterator();
		while(itera.hasNext()){
			rolePrivilegeDao.remove(itera.next());
		}
		roleDao.remove(role);
	}
	
	public List<Role> findByIds(String[] ids) {
		if(ids == null || ids.length == 0) {
			return null;
		}
		Long[] object = new Long[ids.length];
		for(int i = 0;i<ids.length;i++) {
			object[i] = Long.valueOf(ids[i]);
		}
		DetachedCriteria criteria = DetachedCriteria.forClass(Role.class);
		criteria.add(Restrictions.in("id", object));
		return roleDao.findByCriteria(criteria);
	}
	@Override
	public Role findByName(String name) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Role.class);
		criteria.add(Restrictions.eq("name", name));
		List<Role> roles = roleDao.findByCriteria(criteria);
		if(roles != null && roles.size() > 0){
			return roles.get(0);
		}
		return null;
	}
}
